package main

import (
	"context"
	"gitee.com/livo/localfile/server_http"
	"gitee.com/livo/localfile/service"
	"gitee.com/livo/localfile/util"
	"log"
	"os"
	"os/signal"
	"strconv"
	"strings"
	"syscall"
)

//go:generate swag init -g ./main.go
//go:generate rice embed-go  -i "gitee.com/livo/localfile/server_http"

func main() {

	ipPort := util.GetIpAddr() + ":80"
	port := 80
	if len(os.Args) >= 2 {
		ipPort = os.Args[1]
		portIndex := strings.LastIndex(ipPort, ":")
		if portIndex == -1 {
			port = 80
		} else {
			portStr := ipPort[portIndex+1:]
			var err error
			port, err = strconv.Atoi(portStr)
			if err != nil {
				panic(err)
			}
		}
	} else {
		ipPort = util.GetIpAddr() + ":80"
		port = 80
	}

	// 开始服务
	ctx := context.Background()
	var app = service.NewService("http://"+ipPort+"/files", ".")
	httpClose := server_http.InitHttp(ctx, app, port)
	log.Println("服务启动成功 " + "http://" + ipPort)
	// 接收到信号退出
	c := make(chan os.Signal, 1)
	signal.Notify(c, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT, syscall.SIGKILL)
	select {
	case s := <-c:
		switch s {
		case syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT, syscall.SIGKILL:
			// shutdown
			err := httpClose(30)
			if err != nil {
				log.Println(err)
			} else {
				log.Println("服务正常关闭")
			}
			log.Println("服务已关闭")
			return
		case syscall.SIGHUP:
		default:
			return
		}
	}
}
